import { Component, OnInit, Injector, ViewChild, EventEmitter, Output } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { Table } from 'primeng/table';
import { Paginator } from 'primeng/primeng';
import {
    ListDtoExtensionsItem,
    Stock_AccountBaseListDto,
    StockZT_RoomServiceProxy,
    StockZT_BorrowBillItemServiceProxy,
    Stock_BorrowToolingItemListDto,
    Stock_BorrowToolingBaseEditDto
} from '@shared/service-proxies/stock-service-proxies';
import * as _ from 'lodash';
import { ModalDirective } from 'ngx-bootstrap';
import { UserDataPermissionServiceProxy, SessionServiceProxy } from '@shared/service-proxies/stock-service-proxies';
import { finalize } from 'rxjs/operators';
@Component({
    templateUrl: './create-or-edit-tooling-borrow-bill-item-modal.component.html',
    animations: [appModuleAnimation()],
    selector: 'createOrEditToolingBorrowBillModal'
})
export class CreateOrEditToolingBorrowBillModalComponent extends AppComponentBase implements OnInit {
    constructor(
        injector: Injector,
        private _base_SessionServiceProxy: SessionServiceProxy,
        private _billService: StockZT_BorrowBillItemServiceProxy,
        private _userDataPermissionService: UserDataPermissionServiceProxy,
        private _stockZT_RoomServiceProxy: StockZT_RoomServiceProxy,
        private _userDataPermissionServiceProxy: UserDataPermissionServiceProxy
    ) {
        super(injector);
    }
    @ViewChild('dataTable') dataTable: Table;
    @ViewChild('paginator') paginator: Paginator;

    @ViewChild('createOrEditModal') modal: ModalDirective;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
    @Output() modalUpdate: EventEmitter<any> = new EventEmitter<any>();
    @Output() accountShow: EventEmitter<any> = new EventEmitter<any>();
    extensions: Array<ListDtoExtensionsItem>;
    detialExtensions: Array<ListDtoExtensionsItem>;
    f_currentDept; //当前部门
    selectedOutLearder; //审核领导
    optionOutLearder;
    optionInDept;
    selectedInDept; //调入单位
    optionInKeeper;
    selectedInKeeper; //调入单位保管员
    optionInAccounting;
    selectedInAccounting; //调度单位会计
    selectedBill: Array<Stock_BorrowToolingItemListDto>;
    editBill: Stock_BorrowToolingItemListDto;
    billbase = new Stock_BorrowToolingBaseEditDto();
    f_TargetRoomNameOptions;
    miliOutBillList = new Array<Stock_BorrowToolingItemListDto>();
    f_MaterialTypeOptions;
    recipientsNatureOptions;
    userDataPermissions;
    selectedDepts;
    itemid;
    qccard;
    saving = false;
    closed = false;
    active = false;
    billid;
    roomOption;
    f_TargetLocationNameOption;
    f_Warehouse;
    f_StorageArea;
    PlanNumber = '';
    ContractNumber = '';
    ngOnInit() {
        this._billService.getWarehouseCombobox('工装库').subscribe(result => {
            this.roomOption = result.items.map(e => {
                return {
                    lable: e.displayText,
                    value: e.value
                };
            });
        });
        this._base_SessionServiceProxy.getCurrentDept().subscribe(result => {
            // this._tranbillService.getCurrentDept().subscribe(result => {
            this.f_currentDept = result.value; //当前登录人所在单位
            this.billbase.f_Dept = this.f_currentDept;
            //审核领导
            // this._tranbillService.getRoleUser('车间主任', result.value).subscribe(result => {
            //     this.optionOutLearder = result.items.map(e => {
            //         return {
            //             label: e.displayText,
            //             value: e
            //         };
            //     });
            //     this.selectedOutLearder = result.items;
            //     // this.optionOutLearder=  _.concat(new Object({
            //     //     label:'请选择',
            //     //    value: new ComboboxItemDto({
            //     //     displayText:'请选择',
            //     //     isSelected:true,
            //     //     value:''
            //     //    })
            //     // }),this.optionOutLearder);
            // });

            //调入单位会计
            // this._tranbillService.getRoleUser('车间财务', result.value).subscribe(result => {
            //     this.optionInAccounting = result.items.map(e => {
            //         return {
            //             label: e.displayText,
            //             value: e
            //         };
            //     });
            //     this.selectedInAccounting = result.items;
            // });
            //调入单位保管员
            // this._tranbillService.getRoleUser('工装库存保管员', result.value).subscribe(result => {
            //     this.optionInKeeper = result.items.map(e => {
            //         return {
            //             label: e.displayText,
            //             value: e
            //         };
            //     });
            //     this.selectedInKeeper = result.items;
            // });
        });

        this._userDataPermissionService.getUserDataPermissionsForEdit(undefined).subscribe(result => {
            this.optionInDept = result.allDepts.map(e => {
                return {
                    label: e.displayText,
                    value: e
                };
            });
            this.selectedInDept = result.allDepts;
        });
    }
    getStorage() {
        this._billService.getStorageAreaCombobox('工装报废库').subscribe(result => {
            this.f_TargetLocationNameOption = result.items.map(e => {
                return {
                    lable: e.displayText,
                    value: e.value
                };
            });
        });
        //this.miliOutBillList[index].f_TargetRoomCode=this.f_Warehouse;
    }
    getStorageInfo() {
        // this.miliOutBillList[index].f_TargetLocationCode=this.f_StorageArea;
    }
    //从台帐新增调拨数据
    showList(selectedAccounts: Array<Stock_AccountBaseListDto>): void {
        let keepGo = true;
        selectedAccounts.forEach(element => {
            if (element.f_UsableSum! <= 0 && keepGo == true) {
                keepGo = false;
                this.message.warn('可用合计必须大于0！');
            }
        });
        if (keepGo) {
            this.active = true;
            this.addAccoutInfo(selectedAccounts);
            this.modal.show();
        }
    }
    show(id?: string, billitem?: Stock_BorrowToolingItemListDto): void {
        this.closed = false;
        this.active = true;
        this.billid = id;
        if (billitem != null || billitem != undefined) {
            this.itemid = billitem.id;
            this.editBill = billitem;
            //  billitem.f_Sort = 0;
            this.miliOutBillList.push(this.editBill);
        }

        this._billService.getBorrowToolingBaseForEdit(id).subscribe(result => {
            this.billbase = result;

            this.modal.show();
        });
    }

    changeInAccounting() {
        this._userDataPermissionServiceProxy.getUserDataPermissions('Warehouses').subscribe(result => {
            // this.itemContextMenuItems = this.getContextMenuItems();
            this._stockZT_RoomServiceProxy
                .getRoomList('工装库', result.items, this.selectedInDept.displayText, undefined, 1000, 0)
                .subscribe(result => {
                    this.f_TargetRoomNameOptions = result.items.map(e => {
                        return {
                            label: e.f_WarehouseName,
                            value: e
                        };
                    });
                });
        });
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }

    getqccard(event) {
        this.qccard = event;
    }

    onHidden() {
        this.closed = true;
    }

    accountmodalshow() {
        this.close();

        let timer = setInterval(() => {
            if (this.closed) {
                this.accountShow.emit(event);
                clearInterval(timer);
            }
        }, 50);
    }

    delete() {
        if (!this.selectedBill) {
            this.notify.error('请先勾选对应的工装信息');
            return;
        }

        this.selectedBill.forEach(element => {
            let milioutbill = new Stock_BorrowToolingItemListDto();
            milioutbill = _.filter(this.miliOutBillList, { f_Sort: element.f_Sort })[0];
            _.remove(this.miliOutBillList, milioutbill);
        });

        this.selectedBill = null;
    }

    addAccoutInfo(event: Array<Stock_AccountBaseListDto>) {
        if (event) {
            event.forEach(element => { 
                if (!this.miliOutBillList.find(e => element.f_MaterialCode == e.f_MaterialCode)) {
                    let milioutbill = new Stock_BorrowToolingItemListDto();
                    milioutbill.f_MaterialCode = element.f_MaterialCode;
                    milioutbill.f_MaterialName = element.f_MaterialName;
                    milioutbill.f_StorageAreaName = element.f_StorageAreaName;
                    milioutbill.f_StorageAreaCode = element.f_StorageAreaCode;
                    milioutbill.f_Sort = this.miliOutBillList.length;
                    milioutbill.f_UnitPrice = element.f_Price;
                    milioutbill.f_Unit = element.f_UnitId;
                    milioutbill.f_TradeMark = element.f_TradeMark;
                    milioutbill.f_Specification = element.f_Specification;
                    milioutbill.f_WarehouseName = element.f_WarehouseName;
                    milioutbill.f_WarehouseCode = element.f_WarehouseCode;
                    milioutbill.f_TargetRoomCode = element.f_WarehouseCode;
                    milioutbill.f_TargetRoomName = element.f_WarehouseName;
                    milioutbill.f_AccountId = element.id;
                    milioutbill.f_RealUsable = element.f_RealUsable;
                    milioutbill.f_InventSerialID = element.f_InventSerialID;
                    milioutbill.f_CAL_ToolingPictureId = element.f_CAL_ToolingPictureId;
                milioutbill.f_CAL_ProductModel = element.f_CAL_ProductModel;
                milioutbill.f_CAL_ProductPictureId = element.f_CAL_ProductPictureId;
                milioutbill.f_CAL_ToolingWeight = element.f_CAL_ToolingWeight;
                milioutbill.f_CAL_ToolingMaxLoad = element.f_CAL_ToolingMaxLoad;
                milioutbill.f_CAL_ProductModelRemark = element.f_CAL_ProductModelRemark;
                milioutbill.f_CAL_IsAttrition = element.f_CAL_IsAttrition;
                    this.miliOutBillList.push(milioutbill);
                }
            });
        }
        this.show(this.billid, undefined);
    }

    cancel(): void {
        this.close();
        this.miliOutBillList = new Array<Stock_BorrowToolingItemListDto>();
    }

    save(): void {
        this.saving = true;
        // this.billbase.f_AuditLeaderId = this.selectedOutLearder.value;
        // this.billbase.f_AuditLeader = this.selectedOutLearder.displayText;
        // this.billbase.f_AuditAccount = this.selectedInAccounting.displayText;
        // this.billbase.f_AuditAccountId = this.selectedInAccounting.value;
        // this.billbase.f_AuditStoremanId = this.selectedInKeeper.value;
        // this.billbase.f_AuditStoreman = this.selectedInKeeper.displayText;
        // this.billbase.f_ToDept='设备工装处';
        // this.billbase.f_ToDeptId=108;
        this.billbase.f_PlanNumber = this.PlanNumber;
        this.billbase.f_ContractNumber = this.ContractNumber;
        if (this.miliOutBillList.some(pg => pg.f_RealUsable < pg.f_Quantity)) {
            this.notify.error('借用数量不能大于实际可用！');
            this.saving = false;
            return;
        }
        if (this.miliOutBillList.some(element => element.f_Quantity == undefined || element.f_Quantity <= 0)) {
            this.notify.error(this.l('借用数量不正确！'));
            this.saving = false;
            return;
        }
        this.billbase.f_BillName = this.billbase.f_Dept + '工装借用';
        this._billService.createOrUpdateBorrowToolingBase(this.billbase).subscribe(result => {
            this.billbase.id = result;
            this._billService
                .creatBorrowToolingItems(this.miliOutBillList, result)
                .pipe(
                    finalize(() => {
                        this.saving = false;
                    })
                )
                .subscribe(() => {
                    if (this.itemid != null && this.itemid != undefined) {
                        this._billService
                            .deleteBorrowBillItem(this.itemid)
                            .pipe(
                                finalize(() => {
                                    this.saving = false;
                                })
                            )
                            .subscribe(() => {
                                this.notify.success(this.l('更新成功'));
                                this.modalSave.emit(this.billid);
                                this.billid = undefined;
                                this.itemid = undefined;
                            });
                    } else {
                        this.notify.success(this.l('保存成功'));
                        this.modalSave.emit(this.billid);
                        this.billid = undefined;
                        this.itemid = undefined;
                    }
                    this.miliOutBillList = new Array<Stock_BorrowToolingItemListDto>();
                    this.close();
                });
        });
    }
}
